package weaver.ihg.action;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.ihg.util.RolesMembersUtil;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.zwl.common.ToolUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

import static weaver.ihg.util.RolesMembersUtil.ResourceType.HRM;
import static weaver.ihg.util.RolesMembersUtil.RoleLevel.HEADQUARTERS;


/**
 * 分区管理员的权限下发
 */
public class PermissionSet_Action extends ToolUtil implements Action {

    private String className = "PermissionSet_Action";
    private String tableName  = "formtable_main_399";//流程表，该数据为测试库表，正式环境需要替换
    private String roleId  = "84";//角色id，该数据为测试库，正式环境需要替换
    private String tableNameJM  = "uf_rolegroup";//建模表


    private final Logger logger = LoggerFactory.getLogger(PermissionSet_Action.class);

    @Override
    public String execute(RequestInfo requestInfo) {
        BaseBean bb = new BaseBean();
        String requestId = Util.null2String(requestInfo.getRequestid());
        bb.writeLog("-----------------------------分区管理员的权限下发:"+requestId);

        logger.info("PermissionSet_Action_start-------");
        User user = requestInfo.getRequestManager().getUser();

        try {
            RecordSet rs = new RecordSet();
            //执行查询语句，查询数据
            rs.executeQuery("select id from "+ tableName+" where requestid = ?", requestId);

            if(rs.next()){
                String mainid = rs.getString("id");
                logger.info("PermissionSet_Action_rs_mainid:"+mainid);
                RecordSet rsdt = new RecordSet();
                //lineuser条线包含人员(多人力资源)、rolename角色组id、
                String quertSqldt = "select  adminname,lineuser,sfnckhgrw,rolename from "+tableName+"_dt1 where mainid = ?";
                logger.info("PermissionSet_Action_rs_quertSqldt:"+quertSqldt);
                rsdt.executeQuery(quertSqldt,mainid);

                while (rsdt.next()) {
                    String lineuser = rsdt.getString("lineuser");
                    //adminname管理员id
                    String adminname = rsdt.getString("adminname");

                    //是否能查看合规任务
                    String sfnckhgrw = rsdt.getString("sfnckhgrw");
                    //角色名称
                    String rolename = rsdt.getString("rolename");

                    if ("0".equals(sfnckhgrw)){
                        RecordSet recordSet = new RecordSet();
                        recordSet.executeUpdate("update uf_rwtzeq set jszglymd=null,jsmc=null where jsmc= ?",rolename);
                        this.writeDebuggerLog(className,"******************[lineuser:" + lineuser +"]");
                        String updateSql = "update uf_rwtzeq set jszglymd = ? ,jsmc = ? where hdcjr in("+ lineuser+")";
                        recordSet.executeUpdate(updateSql,adminname,rolename);
                    }else if ("1".equals(sfnckhgrw)){
                        RecordSet recordSet = new RecordSet();
                        recordSet.executeUpdate("update uf_rwtzeq set jszglymd=null,jsmc=null where jsmc= ?",rolename);
                        String updateSql = "update uf_rwtzeq set jszglymd = ? ,jsmc = ? where hdcjr in("+ lineuser+") and compliancetasks = 1";
                        recordSet.executeUpdate(updateSql,adminname,rolename);
                    }
                }

                String adminnameSqldt = "select adminname from "+tableNameJM;
                logger.info("PermissionSet_Action_adminnameSqldt:"+adminnameSqldt);
                rsdt.executeQuery(adminnameSqldt);
                //管理员名单
                ArrayList<String> adminnames = new ArrayList<String>();
                while (rsdt.next()){
                    //adminname管理员id
                    String adminname = rsdt.getString("adminname");
                    logger.info("PermissionSet_Action_rs_adminname:"+adminname);
                    if (!"".equals(adminname)){
                        List<String> userIdList = Arrays.asList(adminname.split(","));
                        adminnames.addAll(userIdList);
                    }
                }

                if (adminnames.size()>0){
                    logger.info("PermissionSet_Action_rs_adminnameList:"+adminnames);
                    try {
                        //delete role
                        RecordSet recordSet = new RecordSet();
                        //清空目前已经存在的所有分区管理员角色
                        String selectRole = "select id from HrmRoleMembers where roleId = "+roleId;
                        recordSet.executeQuery(selectRole);
                        ArrayList<String> strings = new ArrayList<>();
                        int colCounts = recordSet.getColCounts();
                        if (colCounts>0){
                            while (recordSet.next()) {
                                strings.add(recordSet.getString("id"));
                            }
                            logger.info("PermissionSet_Action_deleteRoleMembers():"+roleId+","+strings +","+ user);
                            RolesMembersUtil.deleteRoleMembers(roleId,strings , user);
                        }
                        //add role
                        //去重
                        adminnames = new ArrayList<>(new HashSet<>(adminnames));
                        logger.info("PermissionSet_Action_saveRoleMembers():"+roleId+","+adminnames );
                        RolesMembersUtil.saveRoleMembers(roleId,adminnames, RolesMembersUtil.ResourceType.HRM,HEADQUARTERS,user);
                    }catch (Exception e){
                    }
                }
            }



        }catch (Exception e){
            e.printStackTrace();
            requestInfo.getRequestManager().setMessagecontent("Action调用异常["+e.getMessage()+"]，请联系管理员！");
            return "0";
        }
        return SUCCESS;
    }
}
